import { registerOverlay,utils,registerLocale } from "klinecharts";
//自定义圆形
  registerOverlay({
    name: "circle",
    needDefaultPointFigure: true,
    needDefaultXAxisFigure: true,
    needDefaultYAxisFigure: true,
    totalStep: 3,
    createPointFigures: function ({ coordinates }) {
      if (coordinates.length === 2) {
        const xDis = Math.abs(coordinates[0].x - coordinates[1].x);
        const yDis = Math.abs(coordinates[0].y - coordinates[1].y);
        const radius = Math.sqrt(xDis * xDis + yDis * yDis);
        return {
          key: "circle",
          type: "circle",
          attrs: {
            ...coordinates[0],
            r: radius,
          },
          styles: {
            style: "stroke_fill",
          },
        };
      }
      return [];
    },
  });
  //自定义矩形
  registerOverlay({
    name: "rect",
    needDefaultPointFigure: true,
    needDefaultXAxisFigure: true,
    needDefaultYAxisFigure: true,
    totalStep: 3,
    createPointFigures: function ({ coordinates }) {
      if (coordinates.length === 2) {
        //coordinates[0]、coordinates[1]、
        const init_x = (coordinates[0].x <= coordinates[1].x )? coordinates[0].x : coordinates[1].x;
        const init_y = (coordinates[0].y <= coordinates[1].y )? coordinates[0].y : coordinates[1].y;
        const width = Math.abs(coordinates[0].x - coordinates[1].x);
        const height = Math.abs(coordinates[0].y - coordinates[1].y);
        return {
          key: "rect",
          type: "rect",
          attrs: {
            x:init_x,
            y:init_y,
            width,
            height
          },
          styles: {
            style: "stroke_fill",
          },
        };
      }
      return [];
    },
  });
  //自定义矩形
  registerOverlay({
    name: "hollowrect",
    needDefaultPointFigure: true,
    needDefaultXAxisFigure: true,
    needDefaultYAxisFigure: true,
    totalStep: 3,
    createPointFigures: function ({ coordinates }) {
      if (coordinates.length === 2) {
        //coordinates[0]、coordinates[1]、
        const init_x = (coordinates[0].x <= coordinates[1].x )? coordinates[0].x : coordinates[1].x;
        const init_y = (coordinates[0].y <= coordinates[1].y )? coordinates[0].y : coordinates[1].y;
        const width = Math.abs(coordinates[0].x - coordinates[1].x);
        const height = Math.abs(coordinates[0].y - coordinates[1].y);
        return {
          key: "rect",
          type: "rect",
          attrs: {
            x:init_x,
            y:init_y,
            width,
            height
          },
          styles: {
            style: "stroke",
          },
        };
      }
      return [];
    },
  });
  //自定义三角形
  registerOverlay({
    name: "tris",
    needDefaultPointFigure: true,
    needDefaultXAxisFigure: true,
    needDefaultYAxisFigure: true,
    totalStep: 4,
    createPointFigures: function ({coordinates,overlay:{styles}}) {
      if (coordinates.length >= 2) {
        return {
          key: "tris",
          type: "polygon",
          attrs: {
            coordinates
          },
          styles: {
            style: "stroke",
            color:styles.polygon.color
          },
        };
      }
      else {
        return {}
      }
    },
  });
  //自定义头肩
  registerOverlay({
    name: "sevPoints",
    needDefaultPointFigure: true,
    needDefaultXAxisFigure: true,
    needDefaultYAxisFigure: true,
    totalStep: 8,
    createPointFigures: function ({coordinates,bounding,overlay:{styles}}) {
      let firgues = [{
          key: "sevPoints",
          type: "line",
          attrs: {
            coordinates
          },
          styles: {
            style: "solid",
          },
        }];
      let createPointText = (x,y,text) => ({
            key:"savePoint_left_top",
            type:'text',
            attrs:{x,y,text},
            styles:{style: 'stroke_fill', backgroundColor:styles.polygon.color},
          });
        //创建顶部文字
        if(coordinates.length >= 3){
          firgues.push(createPointText(coordinates[1].x -20, coordinates[1].y -20,'左肩'));
        }
        if(coordinates.length >= 5){
          firgues.push(createPointText(coordinates[3].x -20, coordinates[3].y -20,'头部'));
        }
        if(coordinates.length >= 7){
          firgues.push(createPointText(coordinates[5].x -20, coordinates[5].y -20,'右肩'));
        }
        //创建相交区域
        if(coordinates.length >= 7){
          function getIntersectionPoint(line1, line2) {
            // 解方程组
            const x1 = line1[0][0];
            const y1 = line1[0][1];
            const x2 = line1[1][0];
            const y2 = line1[1][1];
            
            const x3 = line2[0][0];
            const y3 = line2[0][1];
            const x4 = line2[1][0];
            const y4 = line2[1][1];
            
            const denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
            
            if (denominator === 0) {
              // 直线平行，没有交点
              return null;
            }
    
            const intersectionX = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / denominator;
            const intersectionY = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / denominator;
            
            return {x:intersectionX,y:intersectionY};
          }      
          try{
            let line1 = [[coordinates[0].x,coordinates[0].y],[coordinates[1].x,coordinates[1].y]];
            let line2 = [[coordinates[2].x,coordinates[2].y],[coordinates[4].x,coordinates[4].y]];
            let line3 = [[coordinates[5].x,coordinates[5].y],[coordinates[6].x,coordinates[6].y]];
            let leftPoint =getIntersectionPoint(line1,line2);
            let rightPoint =getIntersectionPoint(line2,line3);
            if(!leftPoint || !rightPoint) throw new Error();
  
            let polygons = [[leftPoint,coordinates[1],coordinates[2]],[coordinates[2],coordinates[3],coordinates[4]],[rightPoint,coordinates[4],coordinates[5]]];
            polygons.forEach((polygon,i,polygons) =>{
              if((i == 0 && !(Math.abs(leftPoint.x - (coordinates[0].x + coordinates[1].x) / 2) <= Math.abs(coordinates[0].x - (coordinates[0].x + coordinates[1].x) / 2))) 
              || (i == 2 && !(Math.abs(rightPoint.x - (coordinates[5].x + coordinates[6].x) / 2) <= Math.abs(coordinates[5].x - (coordinates[5].x + coordinates[6].x) / 2)))){
                firgues.push({
                  // key: "savePoint_intersect_line",
                  type: "line",
                  attrs: utils.getRayLine(i == 0?[coordinates[2],leftPoint]:[coordinates[4],rightPoint],bounding),
                  styles: {
                    style: "dashed",
                  },
                })
              }
              else{
                firgues.push({
                  key: "savePoint_intersect_area",
                  type: "polygon",
                  attrs: {
                    coordinates:polygon
                  },
                  styles: {
                    style: "stroke_fill",
                    color:styles.polygon.color,
                    borderStyle:'dashed'
                  },
                })
              }
            })
          }
          catch(e){
          }
        }
        return firgues;
    },
  });
  //自定义XABCD
  registerOverlay({
    name: "XABCD",
    needDefaultPointFigure: true,
    needDefaultXAxisFigure: true,
    needDefaultYAxisFigure: true,
    totalStep: 6,
    createPointFigures: function ({coordinates,overlay:{styles}}) {
      let firgues = [{
          key: "XABCD",
          type: "line",
          attrs: {
            coordinates
          },
          styles: {
            style: "solid",
          },
        }];
      let createPointText = (x,y,text) => ({
            key:"XABCD_text",
            type:'text',
            attrs:{x,y,text},
            styles:{style: 'stroke_fill', backgroundColor:styles.polygon.color},
          });
        //创建顶部文字
        if(coordinates.length >= 1){
          firgues.push(createPointText(coordinates[0].x,coordinates[0].y +20,'X'));
        }
        if(coordinates.length >= 2){
          firgues.push(createPointText(coordinates[1].x,coordinates[1].y +20,'A'));
        }
        if(coordinates.length >= 3){
          firgues.push(createPointText(coordinates[2].x,coordinates[2].y +20,'B'));
        }
        if(coordinates.length >= 4){
          firgues.push(createPointText(coordinates[3].x,coordinates[3].y +20,'C'));
        }
        if(coordinates.length >= 5){
          firgues.push(createPointText(coordinates[4].x,coordinates[4].y +20,'D'));
        }
  
        //创建相交区域
        if(coordinates.length >= 5){    
          let polygons = [[coordinates[0],coordinates[1],coordinates[2]],[coordinates[2],coordinates[3],coordinates[4]]];
            polygons.forEach(polygon => firgues.push({
              key: "XABCD_intersect_area",
              type: "polygon",
              attrs: {
                coordinates:polygon
              },
              styles: {
                style: "stroke_fill",
                color:styles.polygon.color,
                borderStyle:'dashed'
              },
            }))
        }
        return firgues;
    },
  });
  //自定义信息线
  registerOverlay({
    name: "infoLine",
    needDefaultPointFigure: true,
    needDefaultXAxisFigure: true,
    needDefaultYAxisFigure: true,
    totalStep: 3,
    // createPointFigures: function (obj) {
    createPointFigures: function (opts) {
      const {overlay:{points,styles},coordinates} = opts;
      // window.that = this;
      // window.opts = opts;
      let firgues = [{
          key: "infoLine",
          type: "line",
          attrs: {
            coordinates
          },
          styles: {
            style: "solid",
          },
        }];
      if(coordinates.length >= 2){
        //创建文本
        let x,y;
        let step = 20;
        let startIndex = 0;
        let endIndex = 1;
        if(coordinates[0].x <= coordinates[1].x){
          startIndex = 0;
          endIndex = 1;
        }
        else {
          startIndex = 1;
          endIndex = 0;
        }
        if(points[startIndex].value < points[endIndex].value){
          //下跌
          x = (coordinates[startIndex].x + coordinates[endIndex].x) / 2;
          y = (coordinates[startIndex].y + coordinates[endIndex].y) / 2;
          step = 20;
        }
        else{
          //上涨
          x = (coordinates[startIndex].x + coordinates[endIndex].x) / 2;
          y = (coordinates[startIndex].y + coordinates[endIndex].y) / 2 - 20;
          step = -20;
        }
        let textList = [
          `${(points[endIndex].value - points[startIndex].value).toFixed(4)} (${((points[endIndex].value / points[startIndex].value - 1)* 100).toFixed(4)}%)`,
          `起点 : ${points[startIndex].value.toFixed(4)}`,
          `终点 : ${points[endIndex].value.toFixed(4)}`,
          `k线数量 : ${points[endIndex].dataIndex - points[startIndex].dataIndex + 1} (${((points[endIndex].timestamp - points[startIndex].timestamp) / (24 * 60 * 60 * 1000)).toFixed(4)} 天)`,
          // `${((points[endIndex].timestamp - points[startIndex].timestamp) / (24 * 60 * 60 * 1000)).toFixed(4)} 天`,
        ]
        textList.forEach((text,i) =>{
          firgues.push({
            key:"infoLine_text",
            type:'text',
            attrs:{x,y:y+step * i,text},
            styles:{style: 'stroke_fill', backgroundColor:styles.polygon.color,color:styles.text.color},
          })
        })
      }
        return firgues;
    },
  });
  //自定义text
  registerOverlay({
    name: "rectText",
    needDefaultPointFigure: true,
    needDefaultXAxisFigure: true,
    needDefaultYAxisFigure: true,
    totalStep: 2,
    // createPointFigures: function (obj) {
    createPointFigures: function (opts) {
      const {overlay:{points,styles,extendData},coordinates} = opts;
      // window.that = this;
      // window.opts = opts;
      let firgues = [];
      if(coordinates.length >= 1){
        //创建文本
        firgues.push({
          key:"rect_text",
          type:'text',
          attrs:{x:coordinates[0].x,y:coordinates[0].y -30,text:extendData,align:'center',baseline:'center'},
          styles:{style:'stroke_fill', borderColor:styles.polygon.color,color:styles.text.color,size:18},
        });
        // // 创建边框
        // let rectX = coordinates[0].x - (extendData.length / 2 * 11 + 11);
        // let rectY = coordinates[0].y - 30;
        // let rectWidth = (extendData.length + 2) * 11;
        // let rectHeight = 30;
        // firgues.push({
        //   key:"rect_text_border",
        //   type:'rect',
        //   attrs:{x:rectX,y:rectY,width:rectWidth,height:rectHeight},
        //   styles:{style:'stroke', borderColor:styles.polygon.color,color:styles.text.color,borderSize:2},
        // })
      }
        return firgues;
    },
  });
    //自定义XABCD
    registerOverlay({
      name: "ABCD",
      needDefaultPointFigure: true,
      needDefaultXAxisFigure: true,
      needDefaultYAxisFigure: true,
      totalStep: 5,
      createPointFigures: function ({coordinates,overlay:{styles}}) {
        let firgues = [{
            key: "ABCD",
            type: "line",
            attrs: {
              coordinates
            },
            styles: {
              style: "solid",
            },
          }];
        let createPointText = (x,y,text) => ({
              key:"ABCD_text",
              type:'text',
              attrs:{x,y,text},
              styles:{style: 'stroke_fill', backgroundColor:styles.polygon.color},
            });
          //创建顶部文字
          if(coordinates.length >= 1){
            firgues.push(createPointText(coordinates[0].x,coordinates[0].y +20,'A'));
          }
          if(coordinates.length >= 2){
            firgues.push(createPointText(coordinates[1].x,coordinates[1].y +20,'B'));
          }
          if(coordinates.length >= 3){
            firgues.push(createPointText(coordinates[2].x,coordinates[2].y +20,'C'));
          }
          if(coordinates.length >= 4){
            firgues.push(createPointText(coordinates[3].x,coordinates[3].y +20,'D'));
          }
    
          //创建相交区域
          if(coordinates.length >= 4){
            function findLineIntersection(x1, y1, x2, y2, x3, y3, x4, y4) {
              // 计算直线1的斜率
              const slope1 = (y2 - y1) / (x2 - x1);
              
              // 计算直线1的截距
              const intercept1 = y1 - slope1 * x1;
              
              // 计算直线2的斜率
              const slope2 = (y4 - y3) / (x4 - x3);
              
              // 计算直线2的截距
              const intercept2 = y3 - slope2 * x3;
              
              // 判断直线是否平行
              if (slope1 === slope2) {
                return null; // 直线平行，无交点
              }
              
              // 计算交点坐标
              const x = (intercept2 - intercept1) / (slope1 - slope2);
              const y = slope1 * x + intercept1;
              
              return {
                point:{ x, y },
                slope1,
                slope2
              }; // 返回交点坐标
            }
            function doLinesIntersect(p1, p2, p3, p4) {
              // 计算直线 p1-p2 和 p3-p4 的斜率
              const slope1 = (p2.y - p1.y) / (p2.x - p1.x);
              const slope2 = (p4.y - p3.y) / (p4.x - p3.x);
            
              // 检查斜率是否相等以确定是否平行
              if (slope1 === slope2) {
                // 如果斜率相等，检查它们是否重合
                return (p1.x === p3.x && p1.y === p3.y) || (p1.x === p4.x && p1.y === p4.y);
              }
            
              // 使用叉积判断两条直线是否相交
              const crossProduct = (p2.x - p1.x) * (p4.y - p3.y) - (p2.y - p1.y) * (p4.x - p3.x);
            
              // 如果叉积为0，则两条直线平行
              if (crossProduct === 0) {
                return false;
              }
            
              // 计算直线 p1-p2 和直线 p3-p4 的截距
              const intercept1 = p1.y - slope1 * p1.x;
              const intercept2 = p3.y - slope2 * p3.x;
            
              // 使用截距和斜率计算交点
              const xIntersection = (intercept2 - intercept1) / (slope1 - slope2);
              const yIntersection = slope1 * xIntersection + intercept1;
            
              // 检查交点是否在两条直线上
              return (
                xIntersection >= Math.min(p1.x, p2.x) && xIntersection <= Math.max(p1.x, p2.x) &&
                xIntersection >= Math.min(p3.x, p4.x) && xIntersection <= Math.max(p3.x, p4.x) &&
                yIntersection >= Math.min(p1.y, p2.y) && yIntersection <= Math.max(p1.y, p2.y) &&
                yIntersection >= Math.min(p3.y, p4.y) && yIntersection <= Math.max(p3.y, p4.y)
              );
            }
            let {point:xPoint,slope1,slope2} = findLineIntersection(coordinates[0].x,coordinates[0].y,coordinates[2].x,coordinates[2].y,coordinates[1].x,coordinates[1].y,coordinates[3].x,coordinates[3].y);
            let polygons;
            if(coordinates[0].y > coordinates[1].y){
              //A在上面
              if(slope2>0){
                polygons = [[coordinates[0],coordinates[1],xPoint]];
              }
              else{
                polygons = [[coordinates[2],coordinates[3],xPoint]];
              }
            }
            else{
              //AC在下面
              if(slope1>0){
                polygons = [[coordinates[0],coordinates[1],xPoint]];
              }
              else{
                polygons = [[coordinates[2],coordinates[3],xPoint]];
              }
            }

            // if(xPoint && !doLinesIntersect(coordinates[0],coordinates[2],coordinates[1],coordinates[3])){
            if(xPoint){
              polygons.forEach(polygon => firgues.push({
                key: "ABCD_intersect_area",
                type: "polygon",
                attrs: {
                  coordinates:polygon
                },
                styles: {
                  style: "stroke_fill",
                  color:styles.polygon.color,
                  borderStyle:'dashed'
                },
              }))
            }
          }
          return firgues;
      },
    });
    
  //语种定义
  registerLocale('zh-CN', {
    time: '时间：',
    open: '开盘价：',
    high: '最高值：',
    low: '最低值：',
    close: '收盘价：',
    volume: '成交量：'
  })
  